package cn.uncode.springcloud.starter.web.result;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import cn.uncode.springcloud.utils.string.StringUtil;

/**
 * @author Juny.ye
 */
public class Message {
    private static final String BUNDLE_NAME = "message"; 

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    private Message() {
    }
    
    public static ResultCode getRCode(String key, Object... params) {
    	String value = null;
    	if(null == params) {
    		value = getString(key);
    	}else{
    		value = getString(key, params);
    	}
    	return buildResultCode(value);
    }

	private static ResultCode buildResultCode(String value) {
		int code = 0;
    	String msg = null;
    	if(StringUtil.isNotBlank(value)) {
    		String[] vlas = value.split("-");
    		if(vlas.length > 1) {
    			if(StringUtil.isNotBlank(vlas[0])) {
    				code = Integer.parseInt(vlas[0]);
        		}
    			if(StringUtil.isNotBlank(vlas[1])) {
    				msg = vlas[1];
        		}
    		}
    	}
    	if(code > 0) {
    		return ResultCode.valueOf(code, msg);
    	}else {
    		return ResultCode.IS_NULL;
    	}
	}

    private static String getString(String key) {
        try {
            return RESOURCE_BUNDLE.getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

    private static String getString(String key, Object... params) {
        try {
            return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

}
